package web.util;

import web.services.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/3/26.
 */

@Component
public class IpUtil {
    @Autowired
    private LocationService locationService;

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取用户当前请求的IP地址
     * @param request
     * @return
     */
    public static String getRemortIP(HttpServletRequest request) {

        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }


    public int findDistrict(HttpServletRequest request){
        String ip=getRemortIP(request);
//        String ip="171.113.102.222";
        try
        {
            URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + ip);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while((line = reader.readLine()) != null)
            {
                result.append(line);
            }
            reader.close();
            ip = result.substring(result.indexOf( "该IP所在地为：" ));
            ip = ip.substring(ip.indexOf( "：") + 1);
            String province = ip.substring(8, ip.indexOf("省"));
            List<Map<String,Object>> list=locationService.getLocationAllList();
            for (Map<String, Object> map : list) {
                String name=map.get("name").toString();
                if(name.indexOf(province)!=-1){
                    return Integer.parseInt(map.get("code").toString());
                }
            }

            String city = ip.substring(ip.indexOf("省") + 1, ip.indexOf("市"));
            System.out.println("pr:"+province);
        }
        catch( Exception e)
        {
            return 0;
        }
        return 0;
    }

    public static String  findDistrictName(HttpServletRequest request){
        String ip=getRemortIP(request);
        //String ip="171.113.102.222";
        try
        {
            URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + ip);
            URLConnection conn = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
            String line = null;
            StringBuffer result = new StringBuffer();
            while((line = reader.readLine()) != null)
            {
                result.append(line);
            }
            reader.close();
            ip = result.substring(result.indexOf( "该IP所在地为：" ));
            ip = ip.substring(ip.indexOf( "：") + 1);
            String province = ip.substring(8, ip.indexOf("省"));
            //String city = ip.substring(ip.indexOf("省") + 1, ip.indexOf("市"));
            //System.out.println("pr:"+province+",city:"+city);
            return province;
        }
        catch( Exception e)
        {
            return "";
        }
    }

    /* 将ip转int */
    public static Long ip2int(String ip) {
        Long num = 0L;
        if (ip == null) {
            return num;
        }
        try {
            ip = ip.replaceAll("[^0-9\\.]", ""); //去除字符串前的空字符
            String[] ips = ip.split("\\.");
            if (ips.length == 4) {
                num = Long.parseLong(ips[0], 10) * 256L * 256L * 256L + Long.parseLong(ips[1], 10) * 256L * 256L + Long.parseLong(ips[2], 10) * 256L + Long.parseLong(ips[3], 10);
                num = num >>> 0;
            }
        } catch (NullPointerException ex) {
            System.out.println(ip);
        }
        return num;
    }

}
